<?php
namespace app\mobile\controller;
use cmf\controller\HomeBaseController;
use think\facade\Validate;
use app\user\model\UserModel;
use app\portal\model\UserModel as UsersModel;
use app\portal\model\UserOrganizeModel;
use think\Db;

class UserController extends HomeBaseController
{
    public function index()
    {
        $user=cmf_get_current_user();
        //dump($user);
        if(!$user){
            $this->redirect('register');
        }else{
            $this->redirect('apply');
        }
    }
    //申请页面
    public function apply(){
        $user=session('user');
        $org_id = input('org_id');
        $model=new UserOrganizeModel();
        if($user){
            $find=$model->where(['user_id'=>$user['id'],'org_id'=>$org_id])->find();

            $is_qianshou = $model->where(['user_id'=>$user['id'],'org_id'=>1])->count();
            $is_zhuomuniao = $model->where(['user_id'=>$user['id'],'org_id'=>2])->count();

            if($find){
                if($find['status']==1){
                    $this->error('您已经是该类志愿者了，不需要在申请了!', url('/mobile'));
                }
                $this->error('您已提交申请!请等待审核!', url('/mobile'));
            }
        }
        $this->assign('is_zhuomuniao',$is_zhuomuniao);
        $this->assign('is_qianshou',$is_qianshou);
        $this->assign('org_id',$org_id);
        return $this->fetch();
    }
    //注册页面
    public function register(){
        return $this->fetch();
    }
    //登录页面
    public function login(){
        return $this->fetch();
    }

    public function ajax_login(){
        $result=[];
        $data=input('post.',null);

        try{
            if(!$data){
                throw new \Exception('请求参数错误');
            }
            $type = $data['type'];
            unset($data['type']);
            if($type==1){
                $rules =[
                    'mobile' => 'require',
                    'code' => 'require|min:4|max:4',
                ];
                $msg = [
                    'mobile.require' => '用户名不能为空',
                    'code.require' => '验证码不能为空',
                    'code.max'     => '密码不能超过4个字符',
                    'code.min'     => '密码不能小于4个字符',
                ];
                $validate = new \think\Validate($rules,$msg);
                if (!$validate->check($data)) {
                    throw new \Exception($validate->getError());
                }

                $usersModel= new UsersModel();
                $log            = $usersModel->doMobile($data);
            }else if($type==0){
                $rules=[
                    'mobile' => 'require',
                    'password' => 'require|min:6|max:32',
                ];
                $msg=[
                    'username.require' => '用户名不能为空',
                    'password.require' => '密码不能为空',
                    'password.max'     => '密码不能超过32个字符',
                    'password.min'     => '密码不能小于6个字符',
                ];
                $validate = new \think\Validate($rules,$msg);
                if (!$validate->check($data)) {
                    throw new \Exception($validate->getError());
                }
                $data['user_pass'] = $data['password'];
                $userModel         = new UserModel();
                $log= $userModel->doMobile($data);
            }

            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $result['errmsg']=lang('LOGIN_SUCCESS');
                    $result['error']=false;
                    break;
                case 1:
                    throw new \Exception(lang('PASSWORD_NOT_RIGHT'));
                case 2:
                    throw new \Exception('账户不存在');
                case 3:
                    throw new \Exception('账号被禁止访问系统');
                default :
                    throw new \Exception('未受理的请求');
            }

        }catch(\Exception $e){
            $result['error']=true;
            $result["errmsg"] =$e->getCode().':'.$e->getMessage();
            $result['file']=$e->getFile();
        }
        return json($result);
    }
    //登录验证
    public function doLogin()
    {
        if ($this->request->isPost()) {
        $data = $this->request->post();
        $user['mobile'] = $data['mobile'];
        if($data['code']){
            $usersModel         = new UsersModel();
            $user['code'] = $data['code'];
            $validate = new \think\Validate([
                'mobile' => 'require',
                'code' => 'require|min:4|max:4',
            ]);
            $validate->message([
                'mobile.require' => '用户名不能为空',
                'code.require' => '验证码不能为空',
                'code.max'     => '密码不能超过4个字符',
                'code.min'     => '密码不能小于4个字符',
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $log            = $usersModel->doMobile($user);
        }
        if($data['password']){
            $userModel         = new UserModel();
            $user['user_pass'] = $data['password'];
            $validate = new \think\Validate([
                'mobile' => 'require',
                'password' => 'require|min:6|max:32',
            ]);
            $validate->message([
                'username.require' => '用户名不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
            ]);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $log= $userModel->doMobile($user);
        }
            //$session_login_http_referer = session('login_http_referer');
            //$redirect                   = empty($session_login_http_referer) ? $this->request->root() : $session_login_http_referer;
            $redirect='/mobile/';
            switch ($log) {
                case 0:
                    cmf_user_action('login');
                    $this->success(lang('LOGIN_SUCCESS'), $redirect);
                    break;
                case 1:
                    $this->error(lang('PASSWORD_NOT_RIGHT'));
                    break;
                case 2:
                    $this->error('账户不存在');
                    break;
                case 3:
                    $this->error('账号被禁止访问系统');
                    break;
                default :
                    $this->error('未受理的请求');
            }
        } else {
            $this->error("请求错误");
        }
    }




    //提交注册
    public function doRegister()
    {
        if ($this->request->isPost()) {
            $rules = [
                'code'     => 'require',
                'password' => 'require|min:6|max:32',

            ];
            $isOpenRegistration = cmf_is_open_registration();
            if ($isOpenRegistration) {
                unset($rules['code']);
            }
            $validate = new \think\Validate($rules);
            $validate->message([
                'code.require'     => '验证码不能为空',
                'password.require' => '密码不能为空',
                'password.max'     => '密码不能超过32个字符',
                'password.min'     => '密码不能小于6个字符',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

//            $captchaId = empty($data['_captcha_id']) ? '' : $data['_captcha_id'];
//            if (!cmf_captcha_check($data['captcha'], $captchaId)) {
//                $this->error('验证码错误');
//            }
//            if (!$isOpenRegistration) {
//                $errMsg = cmf_check_verification_code($data['username'], $data['code']);
//                if (!empty($errMsg)) {
//                    $this->error($errMsg);
//                }
//            }
            if($data['code']!=session($data['username'])){
                $this->error('验证码错误');
            }
            $register          = new UserModel();
            $user['user_pass'] = $data['password'];
            if (Validate::is($data['username'], 'email')) {
                $user['user_email'] = $data['username'];
                $log                = $register->register($user, 3);
            } else if (cmf_check_mobile($data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $register->register($user, 2);
            } else {
                $log = 2;
            }

            switch ($log) {
                case 0:
                    $this->success('注册成功', '/mobile/user/apply');
                    break;
                case 1:
                    $this->error("您的账户已注册过");
                    break;
                case 2:
                    $this->error("您输入的账号格式错误");
                    break;
                default :
                    $this->error('未受理的请求');
            }

        } else {
            $this->error("请求错误");
        }
    }
    //补全信息页面
    public function userinfo(){
        $model=new UserOrganizeModel();
        $org_id = input('org_id');
        $user=session('user');
        $more=Db::name('user')->where('id',$user['id'])->value('more');
        if($user==null){
            $this->assign('org_id',$org_id);
            return $this->fetch('/user/register');
        }elseif( $more==null){
            $district=Db::name('community_district')->select();
            $group=Db::name('organize_child')->select();
            $this->assign('district',$district);
            $this->assign('org_id',$org_id);
            $this->assign('group',$group);
            return $this->fetch();
        }else{
            $find=$model->where(['user_id'=>$user['id'],'org_id'=>$org_id])->find();
            if($find){
                if($find['status']==1){
                    $this->error('您已经是该类志愿者了，不需要在申请了!', url('/mobile'));
                }
                $this->error('您已提交申请!，请等待审核!', url('/mobile'));
            }
            $data=['user_id'=>$user['id'],'org_id'=>$org_id,'child_id'=>$user['community'],'ctime'=>time()];
            $ins=$model->insert($data);
            if($ins){
                $this->success('提交申请信息成功!', url('/mobile'));
            }
        }
    }

    //保存信息
//    public function save_info(){
//        $model=new UserOrganizeModel();
//        $org_id = input('org_id');
//        $input=input();
//        $data=[];
//        $data['user_nickname']=$input['user_nickname'];
//        $data['community']=$input['community'];
//        if(isset($input['more']['group'])){
//            $data['group']=$input['more']['group'];
//        }
//        $data['avatar']=$input['avatar'];
//        $data['more']=json_encode($input['more']);
//        $user_id=cmf_get_current_user_id();
//        $db= new UserModel();
//        $result = $db->where('id',$user_id)->update($data);
//        if ($result === false) {
//            $this->error('修改信息失败!');
//        }
//        $user=session('user');
//        //更改缓存
//        $data['more']=json_decode($data['more'],true);
//        $user=array_replace($user,$data);
//        session('user',$user);
//        $ctime=time();
//        if(isset($input['anothor'])){
//            $user_data=[['user_id'=>$user_id,'org_id'=>1,'child_id'=>$data['community'],'ctime'=> $ctime],
//                ['user_id'=>$user_id,'org_id'=>2,'child_id'=>$data['community'],'ctime'=>time()]];
//        }else{
//            $user_data=['user_id'=>$user['id'],'org_id'=>$org_id,'child_id'=>$data['community'],'ctime'=> $ctime];
//        }
//        $ins=$model->insertAll($user_data);
//
//        if($ins){
//            if($input['car_card']&&$input['img_a']&&$input['img_b']){
//                $car_info=['user_id'=>$user['id'],'car_card'=>$input['car_card'],'img_a'=>$input['img_a'],'img_b'=>$input['img_b']];
//                Db::name('user_info')->insert($car_info);
//            }
//            $this->success('修改信息并成功提交申请!', url('/mobile'));
//        }
//    }


}
